package org.opens.javaskill.thread.threadLocal.apply;

import java.util.stream.IntStream;

/**
 * @Date 2020/9/16 21:04
 * @Created by 99126
 */
public class ContextDesignPattern {

    public static void main(String[] args) {
        final ExecutionTask task = new ExecutionTask();

        IntStream.rangeClosed(1, 5).forEach(i -> {
            new Thread(new ExecutionTask()).start();
        });
    }

}

class ExecutionTask implements Runnable {

    // 模拟访问数据库
    private QueryAction queryAction = new QueryAction();

    // 模拟从三方接口取数据
    private QueryFromHttpAction httpAction = new QueryFromHttpAction();

    @Override
    public void run() {
        // 线程所持有的上下文
        final Context context = new Context();
        queryAction.execute(context);
        httpAction.execute(context);

        System.out.println("the name is " + context.getName() + ", cardId is " + context.getCardId());
    }

}

class QueryAction {

    public void execute(Context context) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String name = "A";
        context.setName(name);
    }

}

class Context {

    private String name;

    private String cardId;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }
}

class QueryFromHttpAction {

    public void execute(Context context) {
        String cardId = getCardIdByName(context.getName());
        context.setCardId(cardId);
    }

    public String getCardIdByName(String name) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = null;
        switch (name) {
            case "A":
                result = "1001";
                break;
            case "B":
                result = "1002";
                break;
            default:
                break;
        }
        return result;
    }

}